package cn.lic.tool.poi.excel.function.impl;

import java.util.Objects;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.lic.tool.poi.excel.ParserUtils;
import cn.lic.tool.poi.excel.function.AbstractFunction;
import cn.lic.tool.poi.excel.function.IFunction;
import cn.lic.tool.poi.excel.function.IFunctionArgument;
import cn.lic.tool.poi.excel.function.IValue;
import cn.lic.tool.poi.excel.function.IValue.Type;

/**
 * 合并单元格
 * @author T_lichuang1_kzx
 *
 */
public class GridMerge extends AbstractFunction implements IGridListener {
	
	public GridMerge() {}
	
	private Object groupVal = null;
	private Sheet sheet = null;
	
	/**
	 * 下一个合并单元格所在行
	 */
	private int nextStartRowNum = 0;
	/**
	 * 合并单元格所在列
	 */
	private int columnNum = 0;
	private JSONArray dataList = new JSONArray();

	public GridMerge(IFunctionArgument[] args) {
		this.args = args;
	}

	@Override
	public IFunction build(IFunctionArgument[] args) {
		return new GridMerge(args);
	}

	@Override
	public void renderRow(JSONObject ctx, Row row) {
		if (dataList.size() == 0) {
			groupVal = this.getArg(1, ctx).castValue(Type.OBJECT);
			nextStartRowNum = row.getRowNum();
			dataList.add(ctx);
		} else if (Objects.equals(groupVal, this.getArg(1, ctx).castValue(Type.OBJECT))) {
			dataList.add(ctx);
		} else {
			int currentRowNum =  row.getRowNum();
			Row marginRow = sheet.getRow(nextStartRowNum);
			JSONObject mctx = new JSONObject();
			mctx.put("dataList", dataList);
			IValue val = this.getArg(0, mctx);
			Cell cell = marginRow.getCell(columnNum, MissingCellPolicy.CREATE_NULL_AS_BLANK);
			ParserUtils.setCellValue(cell, val);
			
			if (dataList.size() > 1) {
				sheet.addMergedRegion(new CellRangeAddress(nextStartRowNum, currentRowNum - 1, columnNum, columnNum));
			}
			
			this.dataList.clear();
			this.dataList.add(ctx);
			groupVal = this.getArg(1, ctx).castValue(Type.OBJECT);
			nextStartRowNum = row.getRowNum();
		}
	}

	@Override
	public void endRender(int rowEndIndex) {
		Row marginRow = sheet.getRow(nextStartRowNum);
		JSONObject mctx = new JSONObject();
		mctx.put("dataList", dataList);
		IValue val = this.getArg(0, mctx);
		Cell cell = marginRow.getCell(columnNum, MissingCellPolicy.CREATE_NULL_AS_BLANK);
		ParserUtils.setCellValue(cell, val);
		if (dataList.size() > 1) {
			sheet.addMergedRegion(new CellRangeAddress(nextStartRowNum, rowEndIndex, columnNum, columnNum));
		}
	}

	@Override
	public void init(JSONObject ctx, Cell cell, Sheet sheet) {
		this.columnNum = cell.getColumnIndex();
		this.sheet = sheet;
	}
}
